<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Session;
use vquery;
use app\model\zhanghao as zh;
use app\model\users as us;
use think\Db;

/**
 * 权限管理
 *
 * @author Administrator
 */
class Role extends Check {

    public function __construct() {
        parent::__construct();
        $left = controller("index");
        $left->left();
    }

    public function manage() {
        $list = db("role")->paginate(10);
        $page = $list->render();
        $this->assign('page', $page);
        $title = "权限管理";
        session("cue", "权限管理");
        $this->assign("title", $title);
        $this->assign("list", $list);
        return $this->fetch();
    }

    //ajax查找子权限

    public function ajaxselect() {
        $fid = input('fid');
        $zlist = Db::name('auth')->where("auth_pid=$fid")->select();
        return json($zlist);
    }

    //ajax查找上级权限

    public function ajaxselects() {
        $aid = input('aid');
        $pid = db("auth")->where("auth_id=$aid")->value("auth_pid");
        return json($pid);
    }

    //添加新的权限
    public function addrole() {
        $title = "Dengeki Bunko AddRole";
        $flist = Db::name('auth')->where("auth_level=0")->select(); //循环所有父级        
        $zlist = Db::name('auth')->where("auth_level!=0")->select(); //循环所有子级


        $arrs = array();
        $cateNodestrue = cache("cateNodestrue");

        if (empty($cateNodestrue)) {
            $res = Db::name('auth')->field("auth_id,auth_name,auth_pid")->select();
            $cateNodestrue = json_encode($this->treeadd($arrs, $res, $pid = 0));
            cache("cateNodestrue", $cateNodestrue, 0);
        }


        //var_dump($cateNodestrue);
        $this->assign("jsonarr", $cateNodestrue);

        $this->assign("flist", $flist);
        $this->assign("title", $title);
        $this->assign("zlist", $zlist);


        return $this->fetch();
    }

    //删除权限
    public function deleterole() {
        $id = input('id');
        if (Db::name('role')->delete($id)) {
            return ["status" => 1, 'message' => "删除成功！"];
        } else {
            return ["status" => 2, 'message' => "删除失败！"];
        }
    }

    //保存权限 (添加新的权限)
    public function save() {
        $auths = input('post.auth/a');
        $data['r_name'] = input('r_name');
        $rule = [
            'r_name|权限名称' => 'require|max:15|unique:role',
        ];
        $message = [
            'r_name.require' => '权限名称不能为空！',
            'r_name.max' => '权限名称长度不正确！',
            'r_name.unique' => '权限名称已存在！',
        ];
//自定义规则
        $res = $this->validate($data, $rule, $message);

        if (true !== $res) {

            return ["status" => -1, 'message' => $res];
        }

        if ($auths == null) {
            return ["status" => -1, 'message' => "请至少勾选一项权限！"];
        }

        $data['r_menu'] = implode(",", $auths);
        $menu = $data['r_menu'];
        //return json($auths);
        if (Db::name('role')->insert($data)) {
            return ["status" => 1, 'message' => "添加成功！"];
        } else {
            return ["status" => 2, 'message' => "添加失败！"];
        }
    }

    public function dinyiarr() {
        $u_rid = cache("rids");
        //$u_rid = session("u_rid");

        $menu = db("role")->where("r_id='$u_rid'")->value("r_menu");

        $arr = explode(",", $menu);

        //获取当前用户所属的权限
        //$arr = ["1", "2", "3", "4", "6"];
        return $arr;
    }

    //修改权限 
    public function updaterole() {
        $id = input("id");
        cache("rids", $id, 3600);
        $list = db("role")->find($id);
        $title = "Dengeki Bunko UpdateRole";
//        $flist = Db::name('auth')->where("auth_level=0")->select(); //循环所有父级        
        $flist = "1";
//        $zlist = Db::name('auth')->where("auth_level!=0")->select(); //循环所有子级
        $zlist = "2";
        $mlist = $list['r_menu'];
        $marr = explode(',', $mlist);
        $this->assign("list", $list);
        $this->assign("flist", $flist);
        $this->assign("title", $title);
        $this->assign("zlist", $zlist);
        $this->assign("marr", $marr);

        $arrs = array();

        session("mlists", $mlist);
//        $cateNodes = cache("cateNodes");
//        if (empty($cateNodes)) {
        $res = Db::name('auth')->field("auth_id,auth_name,auth_pid")->select();
        $cateNodes = json_encode($this->tree($arrs, $res, $pid = 0));
//            cache("cateNodes", $cateNodes, 0);
        // }


        $this->assign("jsonarr", $cateNodes);

        return $this->fetch();
    }

    //修改
    public function update() {
        $auths = input('post.auth/a');
        $rid = input("r_id");
        $data['r_name'] = input('r_name');
        $rule = [
            'r_name|权限名称' => 'require|max:15',
        ];
        $message = [
            'r_name.require' => '权限名称不能为空！',
            'r_name.max' => '权限名称长度不正确！',
        ];
//自定义规则
        $res = $this->validate($data, $rule, $message);

        if (true !== $res) {

            return ["status" => -1, 'message' => $res];
        }

        if ($auths == null) {
            return ["status" => -1, 'message' => "请至少勾选一项权限！"];
        }

        $data['r_menu'] = implode(",", $auths);
        $menu = $data['r_menu'];
        //return json($auths);
        if (Db::name('role')->where("r_id=$rid")->update($data)) {
            return ["status" => 1, 'message' => "保存成功！"];
        } else {
            return ["status" => 2, 'message' => "保存失败，可能无改动！"];
        }
    }

    /**
     * 使用插件修改权限（新）
     */
    public function updatetree() {

        $json = input("json");
        $rid = input("rid");
        $rname = input("r_name");
        if (empty($rname) || trim($rname) == "") {
            return ["status" => 2, 'message' => "请填写权限名称！"];
        }
        //return 111;
        //$json = '[{"title":"基本设置","id":1,"checked":true,"spread":true,"children":[{"title":"首页","id":2,"checked":false,"spread":true,"children":[]}]},{"title":"账单管理","id":4,"checked":true,"spread":true,"children":[{"title":"全部账单","id":6,"checked":false,"spread":true,"children":[]}]},{"title":"系统管理","id":7,"checked":true,"spread":true,"children":[{"title":"添加用户","id":8,"checked":false,"spread":true,"children":[]}]}]';
        $jsonarr = json_decode($json, true);
        $newarr = array();
        foreach ($jsonarr as $k => $v) {
            $newarr[] = $v['id'];
            foreach ($v['children'] as $vv) {
                $newarr[] = $vv['id'];
            }
        }
        $data['r_menu'] = implode(",", $newarr);
        $data['r_name'] = input("r_name");
        //$menu = $data['r_menu'];

        if (Db::name('role')->where("r_id=$rid")->update($data)) {
            cache("cateNodes", null);
            cache("cateNodestrue", null);
            return ["status" => 1, 'message' => "修改成功！"];
        } else {
            return ["status" => 2, 'message' => "修改失败！"];
        }
    }

    /**
     * 使用插件添加权限（新）
     */
    public function addtree() {
        $json = input("json");
        $rname = input("r_name");
        if (empty($rname) || trim($rname) == "") {
            return ["status" => 2, 'message' => "请填写权限名称！"];
        }
        $jsonarr = json_decode($json, true);
        $newarr = array();
        foreach ($jsonarr as $k => $v) {
            $newarr[] = $v['id'];
            foreach ($v['children'] as $vv) {
                $newarr[] = $vv['id'];
            }
        }
        $data['r_menu'] = implode(",", $newarr);
        $data['r_name'] = input("r_name");
        if (Db::name('role')->insert($data)) {
            cache("cateNodes", null);
            cache("cateNodestrue", null);
            return ["status" => 1, 'message' => "添加成功！"];
        } else {
            return ["status" => 2, 'message' => "添加失败！"];
        }
    }

    public function tree($arrs, $data, $pid = 0) {

        foreach ($data as $k => $v) {

            if ($v['auth_pid'] == $pid) {
                if (in_array($v['auth_id'], $this->dinyiarr()) && $v['auth_pid'] != 0) {



                    $arr = array('title' => $v["auth_name"], 'id' => $v['auth_id'], "checked" => true, "spread" => true, 'children' => array());
                } else {

                    $arr = array('title' => $v["auth_name"], 'id' => $v['auth_id'], "spread" => true, 'children' => array());
                }

                $arr['children'] = self::tree($arr["children"], $data, $v['auth_id']);
                array_push($arrs, $arr);
            }
        }
        return $arrs;
    }

    public function treeadd($arrs, $data, $pid = 0) {

        foreach ($data as $k => $v) {

            if ($v['auth_pid'] == $pid) {

                $arr = array('title' => $v["auth_name"], 'id' => $v['auth_id'], "spread" => true, 'children' => array());


                $arr['children'] = self::treeadd($arr["children"], $data, $v['auth_id']);
                array_push($arrs, $arr);
            }
        }
        return $arrs;
    }

}
